<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-button type="primary" @click="back">返回</el-button>
      <el-steps
        :space="200"
        :active="activeindex - 0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addgoodsForm"
        :rules="addgoodsrules"
        ref="addgoodsref"
        label-width="100px"
        label-position="top"
        class="demo-ruleForm"
      >
        <!-- @tab-click="handleClick" -->
        <el-tabs
          v-model="activeindex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addgoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addgoodsForm.goods_price"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addgoodsForm.goods_weight"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addgoodsForm.goods_number"
                type="number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="catelist"
                :props="cateProps"
                v-model="addgoodsForm.goods_cat"
                @change="handlechange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manytabledata" :label="item.attr_name" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="i" v-for="(i,k) in item.attr_vals" :key="k" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlytabledata" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture" multiple :headers="headerObj" @on-success="handlesuccess">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor ref="myTextEditor" v-model="addgoodsForm.goods_introduce"
            style="margin-bottom: 10px;"></quill-editor>
            <el-button type="primary" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
      title="提示"
      :visible.sync="previewdialogVisible"
      width="50%">
      <img :src="previewPath" alt="未找到图片">
    </el-dialog>
  </div>
</template>
<script>
import _ from "lodash";
export default {
  data() {
    return {
      activeindex: "0",
      addgoodsForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        pics:[],
        goods_introduce:"",
        attrs:[],
      },
      addgoodsrules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      catelist: [],
      checkList:[],
      manytabledata:[],
      onlytabledata:[],
      headerObj:{
        Authorization:window.sessionStorage.getItem('token'),
      },
      previewdialogVisible:false,
      previewPath:"",
      editorOption:{

      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 },
      });
      this.catelist = res.data;
    },
    handlechange: function () {
      
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.addgoodsForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    tabClicked: async function () {
      if (this.activeindex === "1") {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,{params: {sel: "many",},});
        res.data.forEach((item)=>{
          item.attr_vals=item.attr_vals.length===0?[]:item.attr_vals.split(" ");
        })
        this.manytabledata=res.data
      }
      else if(this.activeindex === "2") {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,{params: {sel: "only",},});
        this.onlytabledata=res.data;
      }
    },
    handleRemove:function(file) {
      // console.log(file)
      // 1. 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2. 从 pics 数组中，找到这个图片对应的索引值
      const i = this.addgoodsForm.pics.findIndex(x => x.pic === filePath)
      // 3. 调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
      this.addgoodsForm.pics.splice(i, 1)
      console.log(this.addgoodsForm)
    },
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.previewdialogVisible = true
    },
    handlesuccess(response) {
      // 1. 拼接得到一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      // 2. 将图片信息对象，push 到pics数组中
      this.addgoodsForm.pics.push(picInfo)
      console.log(this.addgoodsForm.pics);
    },
    add() {
      this.$refs.addgoodsref.validate(async valid=>{
        if(!valid) return this.$message.error("请填写必要的表单项");
        //执行添加步骤
        const form=_.cloneDeep(this.addgoodsForm)
        form.goods_cat=form.goods_cat.join(",");
        //动态属性
        this.manytabledata.forEach(item=> {
          const mdata={
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(" "),
          }
          this.addgoodsForm.attrs.push(mdata)
        })
        //静态属性
        this.onlytabledata.forEach(item=> {
          const mdata={
            attr_id:item.attr_id,
            attr_value:item.attr_vals,
          }
          this.addgoodsForm.attrs.push(mdata)
        })
        form.attrs=this.addgoodsForm.attrs;
        console.log(form);
        const {data:res}=await this.$http.post("goods",form);
        if(res.meta.status !==201) {
          return this.$message.error("失败")
        }
        this.$message.success("成功")
        this.$router.push("/categories")
      })
    },
    back(){
      this.$router.push('/categories')
    }
  }, 
  computed: {
    cateId() {
      if (this.addgoodsForm.goods_cat.length === 3) {
        return this.addgoodsForm.goods_cat[2];
      }
      return null;
    },
  },
};
</script>
<style scoped>
* {
  margin: 0;
  padding: 0;
}
.el-breadcrumb {
  margin-left: 170px;
  margin-top: 20px;
  margin-bottom: 20px;
}
.box-card {
  width: 1200px;
  margin: 0 auto;
}
.el-button {
  margin-bottom: 10px;
}
.el-row {
  margin-bottom: 10px;
}
.el-pagination {
  margin-top: 20px;
}
.el-tabs {
  margin-top: 40px;
  margin-left: -20px;
}
</style>